<template>
  <div class="editWrapper">
    <div class="issueNewStrategy">
      <h3 class="title">发布新攻略</h3>
      <p class="share">分享你的个人游记,让更多人看到哦!</p>
      <el-form :model="form" ref="form" :rules="rules" class="demo-ruleForm">
        <!-- 标题 -->
        <el-form-item prop="title" class="inputTitle">
          <el-input placeholder="请输入标题" v-model="form.title"></el-input>
        </el-form-item>

        <!-- 富文本框编辑 -->

        <el-form-item prop="content" class="ql-editor">
          <client-only>
            <VueEditor
              v-model="form.content"
              :useCustomImageHandler="true"
              @image-added="imgUpload"
              ref= "content"
            />
          </client-only>
        </el-form-item>

        <!-- 选择城市 -->
        <el-form-item label="选择城市" style="width: 40%" prop="selectCity">
          <el-autocomplete
            :trigger-on-focus="false"
            :highlight-first-item="true"
            :fetch-suggestions="queryCitySearch"
            v-model="form.selectCity"
            placeholder="请输入搜索游玩城市"
            @select="handleSelectCity"
          ></el-autocomplete>
        </el-form-item>

        <!-- 提交发布按钮 -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit(form)">发布</el-button>
          或者 <span class="save" @click="handleSave">保存到草稿</span>
        </el-form-item>
      </el-form>

      <!-- 登录/注册页面 -->
      <div class="container" v-if="login" >
        <!-- 主要内容 -->
        <el-row type="flex" justify="center" align="middle" class="main">
          <div class="form-wrapper">
            <!-- 表单头部tab -->
            <el-row type="flex" justify="center" class="tabs">
              <span
                :class="{ active: currentTab === index }"
                v-for="(item, index) in [`登录`, `注册`]"
                :key="index"
                @click="handleChangeTab(index)"
              >
                {{ item }}
              </span>
            </el-row>

            <!-- 登录功能组件 -->
            <LoginForm v-if="currentTab == 0" @sendBool="getBool"/>

            <!-- 注册功能组件 -->
            <RegisterForm v-if="currentTab == 1" />
          </div>
        </el-row>
      </div>
    </div>
    <!-- 右边的草稿箱 -->
    <!-- $store.state.save.saveList.length  获取草稿箱储存vuex 的数组长度 -->
    <div class="rightEdit">
      <div class="draft">
        草稿箱 <span>({{ $store.state.save.saveList.length }})</span>
      </div>
      <EditDraft @editPost="item" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentTab: 0,
      login: false,
      form: {
        title: "",
        content: "",
        selectCity: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入标题名称", trigger: "blur" },
          {
            min: 1,
            max: 30,
            message: "请输入不超过30个字符的标题内容",
            trigger: "blur",
          },
        ],

        selectCity: [
          { required: true, message: "请选择游玩的城市", trigger: "blur" },
        ],
      },
    };
  },
  created() {},

  methods: {
    //显示隐藏登录表单
    getBool(val){
this.login=val
console.log('俺看到看到了扩散到了扩散',val);

    },
    // 从子组件那里获取item参数给父页面 (编辑)
    item(item) {
      console.log("编辑页面", item);
      this.form = { ...item };
    },

    //   发布按钮
    onSubmit(form) {
      console.log("发布按钮");
      if (this.form.title.trim() === "") {
        this.$message.closeAll();
        return this.$message.warning("标题不能为空");
      }


      if (this.form.content.length == 0) {
        this.$message.closeAll();
        return this.$message.warning("内容不能为空");
      }
      

      if (this.form.selectCity.trim() === "") {
        this.$message.closeAll();
        return this.$message.warning("城市名字不能为空");
      }
      if (this.$store.state.user.userInfo.token) {
        this.$axios({
          method: "post",
          url: "/posts",
          headers: {
            Authorization: "Bearer " + this.$store.state.user.userInfo.token,
          },
          data: {
            content: this.form.content,
            title: this.form.title,
            city: this.form.selectCity,
          },
        }).then((res) => {
          console.log("提交数据");
          console.log(res.data);

          if (res.data.message == "新增成功") {
            this.$message.success("旅游攻略发布成功");
            // this.$router.push("/post");
            this.login = false;
          }
        });
      } else {
        this.$message.warning("请先登录");
        this.login = true;
      }
    },

    //富文本框内图片上传
    imgUpload(file, Editor, cursorLocation, resetUploader) {
      console.log("图片上传自定义处理函数");
      console.log(file);
      // 1. 上传图片, 获取地址
      let data = new FormData();
      data.append("files", file);
      this.$axios({
        method: "post",
        url: "/upload",
        data,
      }).then((res) => {
        const url = this.$axios.defaults.baseURL + res.data[0].url;
        console.log(url);
        //2.把图片作为 img标签,放入到编辑器 指定的 content 当中
        Editor.insertEmbed(cursorLocation, "image", url);
        resetUploader();
      });
    },

    //  加载城市列表页面
    loadCityList(queryString, showList) {
      if (!queryString) {
        showList([
          {
            value: "请输入关键字",
          },
        ]);
        return;
      }

      // 远程服务器获取城市列表
      this.$axios({
        url: "/airs/city",
        params: {
          name: queryString,
        },
      }).then((res) => {
        console.log(res);
        const data = res.data.data
          .filter((city) => {
            return city;
          })
          .map((city) => {
            // 之前这里是直接获取数据, value 是以 name 作为基础
            // 用来显示建议列表, 只需要在赋值 value 的时候,
            return {
              ...city,
              value: city.name,
            };
          });
        showList(data);
      });
    },
    //选择城市
    handleSelectCity(item) {
      console.log(item);
      this.form.selectCity = item.name;
    },

    // 显示搜索建议
    queryCitySearch(queryString, showList) {
      // console.log("搜索建议回调函数");
      this.loadCityList(queryString, showList);
    },

    //保存到草稿
    handleSave() {
      console.log("保存到草稿");
      if (this.form.title.trim() === "") {
        this.$message.closeAll();
        return this.$message.warning("标题不能为空");
      }
      if (this.form.content.trim() === "") {
        this.$message.closeAll();
        return this.$message.warning("内容不能为空");
      } else {
        this.$message.closeAll();
        this.$store.commit("save/addSave", {...this.form } );                                    //在vuex中不能直接拿v-model的数据局增删改查,必须解构之后才能进行
        this.$message.success("保存成功");
      }
    },

    handleChangeTab(index) {
      this.currentTab = index;
    },
  },
};
</script>

<style lang="less" scoped>
.editWrapper {
  display: flex;
  justify-content: space-around;
  width: 1000px;
  margin: 0 auto;
  .issueNewStrategy {
    padding-right: 25px;
    .title {
      font-weight: 400;
      font-size: 22px;
      margin: 10px 0;
    }
    .share {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }
    .inputTitle{
      width: 750px;
    }
    .save {
      color: #ffa500;
      cursor: pointer;
    }
    /deep/.ql-editor{
      padding-left: 0;
      padding-right: 0;
    }
    /deep/ #quill-container {

      height: 400px;
      padding: 10px;
    }
    /deep/.el-button {
      padding: 8px 12px;
    }
    /deep/.ql-formats {
      line-height: 1;
    }
  }
}
.rightEdit {
  margin-top: 15px;
  width: 225px;
  height: 100%;
  padding: 10px;
  border: 1px solid #e1e1e1;
  .draft {
    margin: 5px 0;
    font-size: 16px;
    color: #666666;
  }
 
}

// 注册页面
.container {
  .main {
    height: 100%;
    margin: 0 auto;
    position: relative;

    .form-wrapper {
      width: 400px;
      margin: 0 auto;
      background: #fff;
      box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;

      /deep/ .el-input {
        width: 100% !important;
      }

      .tabs {
        span {
          display: block;
          width: 50%;
          height: 50px;
          box-sizing: border-box;
          border-top: 2px #eee solid;
          background: #eee;
          line-height: 48px;
          text-align: center;
          cursor: pointer;
          color: #666;

          &.active {
            color: orange;
            border-top-color: orange;
            background: #fff;
            font-weight: bold;
          }
        }
      }
    }
  }
}
</style>